import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const _router = res.data;
          // const _router = [
          //   {
          //     name: "Shelves",
          //     path: "/shelves",
          //     hidden: false,
          //     redirect: "noRedirect",
          //     component: "Layout",
          //     alwaysShow: true,
          //     meta: {
          //       title: "产品货架管理",
          //       noCache: false,
          //       icon: 'shelves_icon',
          //       link: null,
          //     },
          //     children: [
          //       {
          //         name: "Node",
          //         path: "node",
          //         hidden: false,
          //         component: "shelves/node/index",
          //         meta: {
          //           title: "节点管理",
          //           noCache: false,
          //           link: null,
          //         },
          //       },
          //       {
          //         name: "PageManagemment",
          //         path: "pageManagemment",
          //         hidden: false,
          //         component: "shelves/pageManagemment/index",
          //         meta: {
          //           title: "页面管理",
          //           noCache: false,
          //           link: null,
          //         },
          //       },
          //       {
          //         name: "offerManage",
          //         path: "offer-manage",
          //         hidden: false,
          //         component: "shelves/offerManage/index",
          //         meta: {
          //           title: "报价管理",
          //           noCache: false,
          //           link: null,
          //         },
          //       }
          //     ]
          //   },
          //   {
          //     name: "EnterpriseShowen",
          //     path: "/enterpriseShowen",
          //     hidden: false,
          //     redirect: "noRedirect",
          //     component: "Layout",
          //     alwaysShow: true,
          //     meta: {
          //       title: "企业展示管理",
          //       icon: "enterpriseShowen_icon",
          //       noCache: false,
          //       link: null,
          //     },
          //     children: [
          //       {
          //         name: "Node",
          //         path: "node",
          //         hidden: false,
          //         component: "enterpriseShowen/node/index",
          //         meta: {
          //           title: "节点管理",
          //           noCache: false,
          //           link: null,
          //         },
          //       },
          //       {
          //         name: "PageManagemment",
          //         path: "pageManagemment",
          //         hidden: false,
          //         component: "enterpriseShowen/pageManagemment/index",
          //         meta: {
          //           title: "页面管理",
          //           noCache: false,
          //           link: null,
          //         },
          //       }
          //     ]
          //   },
          //   {
          //     path: '',
          //     component: 'Layout',
          //     redirect: 'dictionaryManage',
          //     children: [
          //       {
          //         path: 'dictionaryManage',
          //         component: 'dictionaryManage/index.vue',
          //         name: 'dictionaryManage',
          //         meta: { title: '字典管理', icon: 'dictionary_manage_icon', affix: true }
          //       }
          //     ]
          //   },
          //   {
          //     path: '',
          //     component: 'Layout',
          //     redirect: 'planManage',
          //     children: [
          //       {
          //         path: 'planManage',
          //         component: 'planManage/index.vue',
          //         name: 'planManage',
          //         meta: { title: '方案管理', icon: 'plan_manage_icon', affix: true }
          //       }
          //     ]
          //   },
          //   {
          //     path: '',
          //     component: 'Layout',
          //     redirect: 'templateManage',
          //     children: [
          //       {
          //         path: 'templateManage',
          //         component: 'templateManage/index.vue',
          //         name: 'planManage',
          //         meta: { title: '模板管理', icon: 'plan_manage_icon', affix: true }
          //       }
          //     ]
          //   },
          //   {
          //     name: "approvalManage",
          //     path: "/approvalManage",
          //     hidden: false,
          //     redirect: "noRedirect",
          //     component: "Layout",
          //     alwaysShow: true,
          //     meta: {
          //       title: "审批管理",
          //       icon: "approval_manage_icon",
          //       noCache: false,
          //       link: null,
          //     },
          //     children: [
          //       {
          //         name: "processManage",
          //         path: "processManage",
          //         hidden: false,
          //         component: "approvalManage/processManage/index",
          //         meta: {
          //           title: "流程管理",
          //           noCache: false,
          //           link: null,
          //         },
          //       },
          //       {
          //         name: "processArticulated",
          //         path: "processArticulated",
          //         hidden: false,
          //         component: "approvalManage/processArticulated/index",
          //         meta: {
          //           title: "流程挂接",
          //           noCache: false,
          //           link: null,
          //         },
          //       },
          //       {
          //         name: "waitingApproval",
          //         path: "waitingApproval",
          //         hidden: false,
          //         component: "approvalManage/waitingApproval/index",
          //         meta: {
          //           title: "待审批",
          //           noCache: false,
          //           link: null,
          //         },
          //       },
          //       {
          //         name: "completeApproval",
          //         path: "completeApproval",
          //         hidden: false,
          //         component: "approvalManage/completeApproval/index",
          //         meta: {
          //           title: "已审批",
          //           noCache: false,
          //           link: null,
          //         },
          //       },
          //       {
          //         name: "completeSubmit",
          //         path: "completeSubmit",
          //         hidden: false,
          //         component: "approvalManage/completeSubmit/index",
          //         meta: {
          //           title: "已提交",
          //           noCache: false,
          //           link: null,
          //         },
          //       }
          //     ]
          //   },
          //   {
          //     name: "systemManage",
          //     path: "/systemManage",
          //     hidden: false,
          //     redirect: "noRedirect",
          //     component: "Layout",
          //     alwaysShow: true,
          //     meta: {
          //       title: "系统管理",
          //       icon: "system_manage_icon",
          //       noCache: false,
          //       link: null,
          //     },
          //     children: [
          //       {
          //         name: "runningWaterCoding",
          //         path: "runningWaterCoding",
          //         hidden: false,
          //         redirect: "noRedirect",
          //         component: 'ParentView',
          //         alwaysShow: true,
          //         meta: {
          //           title: "流水编码",
          //           noCache: false,
          //           link: null,
          //         },
          //         children: [
          //           {
          //             path: 'codingRulesSet',
          //             name: 'codingRulesSet',
          //             hidden: false,
          //             component: 'systemManage/runningWaterCoding/codingRulesSet/index',
          //             meta: {
          //               title: '编码规则设置',
          //               noCache: false,
          //               link: null
          //             },
          //           },
          //           {
          //             path: 'serialNumberSet',
          //             name: 'serialNumberSet',
          //             hidden: false,
          //             component: 'systemManage/runningWaterCoding/serialNumberSet/index',
          //             meta: {
          //               title: '流水号设置',
          //               noCache: false,
          //               link: null
          //             }
          //           },
          //           {
          //             path: 'codingRuleLinkage',
          //             name: 'codingRuleLinkage',
          //             hidden: false,
          //             component: 'systemManage/runningWaterCoding/codingRuleLinkage/index',
          //             meta: {
          //               title: '编码规则关联',
          //               noCache: false,
          //               link: null
          //             }
          //           }
          //         ]
          //       },
          //       {
          //         name: "permissionsManage",
          //         path: "permissionsManage",
          //         hidden: false,
          //         redirect: "noRedirect",
          //         component: 'ParentView',
          //         alwaysShow: true,
          //         meta: {
          //           title: "权限管理",
          //           noCache: false,
          //           link: null,
          //         },
          //         children: [
          //           {
          //             path: 'menuManage',
          //             name: 'menuManage',
          //             hidden: false,
          //             component: 'systemManage/permissionsManage/menuManage/index',
          //             meta: {
          //               title: '菜单管理',
          //               noCache: false,
          //               link: null
          //             },
          //           },
          //           {
          //             path: 'roleManage',
          //             name: 'roleManage',
          //             hidden: false,
          //             component: 'systemManage/permissionsManage/roleManage/index',
          //             meta: {
          //               title: '角色管理',
          //               noCache: false,
          //               link: null
          //             }
          //           },
          //           {
          //             path: 'userAuthorization',
          //             name: 'userAuthorization',
          //             hidden: false,
          //             component: 'systemManage/permissionsManage/userAuthorization/index',
          //             meta: {
          //               title: '用户授权',
          //               noCache: false,
          //               link: null
          //             }
          //           }
          //         ]
          //       },
          //       {
          //         name: "logManage",
          //         path: "logManage",
          //         hidden: false,
          //         redirect: "noRedirect",
          //         component: "ParentView",
          //         alwaysShow: true,
          //         meta: {
          //           title: "日志管理",
          //           noCache: false,
          //           link: null,
          //         },
          //         children: [
          //           {
          //             name: "operlog",
          //             path: "operlog",
          //             hidden: false,
          //             component: "systemManage/logManage/operLog/index",
          //             meta: {
          //               title: "操作日志",
          //               noCache: false,
          //               link: null,
          //             },
          //           },
          //           {
          //             name: "loginLog",
          //             path: "loginLog",
          //             hidden: false,
          //             component: "systemManage/logManage/loginLog/index",
          //             meta: {
          //               title: "登录日志",
          //               noCache: false,
          //               link: null,
          //             },
          //           },
          //         ],
          //       },
          //     ]
          //   }
          // ]
          // const sdata = JSON.parse(JSON.stringify(res.data))
          // const rdata = JSON.parse(JSON.stringify(res.data))
          const sdata = JSON.parse(JSON.stringify(_router));
          const rdata = JSON.parse(JSON.stringify(_router));
          const sidebarRoutes = filterAsyncRouter(sdata)
          const rewriteRoutes = filterAsyncRouter(rdata, false, true)
          const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
          rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
          router.addRoutes(asyncRoutes);
          commit('SET_ROUTES', rewriteRoutes)
          commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
          commit('SET_DEFAULT_ROUTES', sidebarRoutes)
          commit('SET_TOPBAR_ROUTES', sidebarRoutes)
          resolve(rewriteRoutes)
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    }
  })
  return res
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
    return (resolve) => require([`@/views/${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}

export default permission
